<template>
  <view class="page">
    <!-- 轮播图 -->
    <view class="swiper-container">
      <swiper
        :indicator-dots="true"
        :autoplay="false"
        :interval="3000"
        :duration="500"
        indicator-color="#ffffff33"
        indicator-active-color="#ffffff"
        class="swiper-body">
        <swiper-item v-for="(slide, index) in swiperList" :key="index">
          <view class="swiper-item">
            <image
              :src="completeImgPath(slide.image)"
              mode="aspectFit"
              class="swiper-img" />
            <view class="swiper-desc">
              <text class="swiper-title">{{ slide.title }}</text>
              <text class="swiper-subtitle">{{ slide.simpleDesc }}</text>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>

    <!-- 商品分类 -->
    <view class="category">
      <text class="category-title">商品分类</text>
      <view class="category-list">
        <view
          class="category-item"
          v-for="(item, index) in categoryList"
          :key="index"
          @click="selectCategory(item._id)"
          :class="{ active: activeCategoryId === item._id }">
          <view class="category-icon">
            <uni-icons
              type="list"
              size="40"
              :color="
                activeCategoryId === item._id ? '#ff8a3c' : '#000'
              "></uni-icons>
          </view>
          <text class="category-name">{{ item.classifyname }}</text>
        </view>
      </view>
    </view>

    <!-- 热门商品 -->
    <view class="hot-products">
      <view class="hot-header">
        <text class="hot-title">热门商品</text>
        <view class="sort">
          <text class="sort-text">排序：</text>
          <view class="product-select">
            <uni-data-select
              v-model="SortSelectData"
              :localdata="SortData"
              @change="selectSortChange"></uni-data-select>
          </view>

          <uni-icons type="list" size="24" @click="changeFlex"></uni-icons>
        </view>
      </view>
      <scroll-view
        style="height: 900px"
        scroll-y="true"
        @scrolltolower="onScrolltolower">
        <view class="products-list">
          <view
            class="products-item"
            :style="{
              width: isChangeFlex ? '48%' : '100%',
            }"
            v-for="(item, index) in productList"
            :key="item._id"
            @click="selectProduct(item._id)">
            <view
              class="products-img-container"
              :style="{
                height: isChangeFlex ? '150px' : '250px',
              }">
              <image
                :src="completeImgPath(item.mainImage)"
                style="width: 100%; height: 100%; object-fit: contain" />
              <text class="products-tag hot" v-if="item.isHot">热销</text>
              <text class="products-tag new" v-if="index == 1">新品</text>
            </view>
            <view class="products-content-container">
              <text class="products-name">{{ item.name }}</text>
              <text class="products-desc">{{ item.simpleDesc }}</text>
              <text class="products-price">￥{{ item.sellingPrice }}</text>
            </view>
          </view>
        </view>
        <uni-load-more color="#007AFF" :status="loadStatus" />
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { onShow, onLoad } from "@dcloudio/uni-app";
import API from "@/api/index.js";
import { completeImgPath } from "@/utils/common.js";

const loadStatus = ref("more");
const onScrolltolower = async () => {
  console.log(
    "onScrolltolower",
    productList.value.length,
    pageData.value.total
  );
  if (loadStatus.value == "more") {
    if (productList.value.length < pageData.value.total) {
      pageData.value.page += 1;
      await getProductList();
    }
  }
};

// 定义分类类型
interface Category {
  _id?: string;
  classifyname: string;
  isShow: boolean;
  sort?: number;
}

// 定义产品类型
interface ProductType {
  _id?: string;
  name: string;
  description: string;
  categoryId: string;
  categoryName?: string;
  status: string;
  statusName: string;
  sellingPrice?: number;
  originalPrice?: number;
  mainImage: string;
  detailImages?: string[];
  features?: string[];
  ingredients: string;
  simpleDesc?: string;
  isHot: boolean;
}

// 定义分类下拉类型
interface SelectType {
  value: string;
  text: string;
}

// 定义轮播
interface SwiperType {
  id: string;
  image: string;
  title: string;
  simpleDesc: string;
}

const activeCategoryId = ref<string>("");

// 状态定义
const searchText = ref("");
const cartCount = ref(3);
const currentSortIndex = ref(0);

// 轮播数据
const swiperList = ref<SwiperType[]>([]);

const isChangeFlex = ref(true);

// 分类数据列表
const categoryList = ref<Category[]>([]);

//商品数据列表
const productList = ref<ProductType[]>([]);
const pageData = ref({
  page: 1,
  total: 0,
  pageSize: 10,
});
const resetPage = () => {
  pageData.value = {
    page: 1,
    total: 0,
    pageSize: 10,
  };
};
const isLoading = ref(false); // 是否正在加载中
const isAllLoaded = ref(false); // 是否已加载全部数据

// onMounted(async () => {
//   await getCategoryList();
//   await getProductList();
//   swiperList.value = productList.value.slice(0, 3).map((elem) => {
//     return {
//       id: elem._id,
//       image: elem.mainImage,
//       title: elem.name,
//       subtitle: elem.description,
//     };
//   });
// });

onShow(async () => {
  resetPage();
  productList.value = [];
  await getCategoryList();
  await getProductList();
  swiperList.value = productList.value.slice(0, 3).map((elem) => {
    return {
      id: elem._id,
      image: elem.mainImage,
      title: elem.name,
      simpleDesc: elem.simpleDesc,
    };
  });
});

// 判断是否为微信小程序环境
const checkWechatEnv = () => {
  try {
    const systemInfo = uni.getSystemInfoSync();
    console.log(2222, systemInfo);
    return systemInfo.uniPlatform === "mp-weixin";
  } catch (e) {
    console.error("获取系统信息失败:", e);
    return false;
  }
};

const getUserInfo = () => {
  // 先判断是否为微信小程序环境
  const isWechatMiniProgram = checkWechatEnv();
  if (isWechatMiniProgram) {
    uni.getUserInfo({
      success(res) {
        uni.setStorageSync("userInfo", res.userInfo);
        console.log("已获取用户信息:", res.userInfo);
      },
      fail(err) {
        console.log("获取用户信息失败:", err);
      },
    });
  }
};

//获取微信用户信息
// getUserInfo();

//获取分类列表
const getCategoryList = async () => {
  const res = await API.category.getCategoryListApi({ isShow: true });
  if (res.success && res.data.items && res.data.items.length > 0) {
    categoryList.value = res.data.items;
  }
};

//获取商品列表
const getProductList = async () => {
  loadStatus.value = "loading";
  const params: any = {
    page: pageData.value.page,
    pageSize: pageData.value.pageSize,
  };

  if (SortSelectData.value) {
    params.sort = SortSelectData.value;
  }

  if (activeCategoryId.value) {
    params.categoryId = activeCategoryId.value;
  }

  console.log(111111111, activeCategoryId.value, params);

  const res = await API.product.getProductListApi(params);
  if (res.success && res.data.items && res.data.items.length > 0) {
    productList.value.push(...res.data.items);
    pageData.value.total = res.data.meta.totalItems;
    if (productList.value.length < pageData.value.total) {
      loadStatus.value = "more";
    } else {
      loadStatus.value = "noMore";
    }
  } else {
    loadStatus.value = "noMore";
  }
};

const selectCategory = async (value: string) => {
  console.log(value);
  if (activeCategoryId.value == value) {
    activeCategoryId.value = "";
  } else {
    activeCategoryId.value = value;
  }
  resetPage();
  productList.value = [];
  await getProductList();
};

const changeFlex = (value: string) => {
  isChangeFlex.value = !isChangeFlex.value;
};

const SortSelectData = ref("");
const SortData = ref<SelectType[]>([
  {
    value: "new",
    text: "最新上架",
  },
  {
    value: "priceAsc",
    text: "价格从低到高",
  },
  {
    value: "priceDesc",
    text: "价格从高到低",
  },
]);
const selectSortChange = async (value: string) => {
  // console.log("selectSortChange", value);
  resetPage();
  productList.value = [];
  await getProductList();
};

const selectProduct = async (id: string) => {
  console.log(1111111111, id);
  uni.navigateTo({
    url: `/pages/manage/productDetail?id=${id}`,
  });
};
</script>

<style lang="scss" scoped>
.page {
  background-color: #fff8f0;
  min-height: 100vh;
}

.swiper-container {
  overflow: hidden;
  height: 250px;
  .swiper-body {
    height: 100%;
  }
  .swiper-item {
    position: relative;
    height: 100%;
    .swiper-img {
      width: 100%;
      height: 100% !important;
      // object-fit: contain;
    }

    .swiper-desc {
      position: absolute;
      bottom: 20px;
      left: 20px;
      color: #fff;
      z-index: 10;

      .swiper-title {
        font-size: 20px;
        font-weight: 600;
        display: block;
        margin-bottom: 5px;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
      }

      .swiper-subtitle {
        font-size: 14px;
        display: block;
        margin-bottom: 10px;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
      }

      .swiper-btn {
        background-color: rgba(255, 107, 107, 0.9);
        color: #fff;
        border-radius: 20px;
        padding: 6px 18px;
        font-size: 14px;
        border: none;
        transition: background-color 0.3s;

        &:hover {
          background-color: #ff6b6b;
        }
      }
    }

    &::after {
      content: "";
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 60%;
      background: linear-gradient(transparent, rgba(0, 0, 0, 0.5));
    }
  }
}

.category {
  padding: 5px;
  margin-top: 10px;
  border-radius: 8px;
  margin-left: 15px;
  margin-right: 15px;

  .category-title {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 15px;
    display: block;
    color: #5d4037;
  }

  .category-list {
    display: flex;
    gap: 10px;
    overflow-x: scroll;
    &::-webkit-scrollbar {
      display: none;
    }

    .category-item {
      height: 120px;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 5px;
      border-radius: 5px;
      background-color: #fff;
      &.active {
        .category-name {
          color: #ff8a3c;
          font-weight: 500;
        }
      }

      .category-icon {
        width: 80px;
        height: 80px;
        margin-bottom: 6px;
        background-color: #fff8f0;
        border-radius: 40px;
        text-align: center;
        line-height: 80px;
      }

      .category-name {
        font-size: 18px;
        color: #5d4037;
      }
    }
  }
}

.hot-products {
  margin-top: 5px;
  border-radius: 8px;
  margin-left: 15px;
  margin-right: 15px;

  .hot-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 5px;
    border-bottom: 1px solid #f5f5f5;

    .hot-title {
      font-size: 24px;
      font-weight: 600;
      color: #5d4037;
    }

    .sort {
      display: flex;
      align-items: center;

      .product-select {
        width: 220rpx;
        margin-right: 10px;
      }

      .sort-text {
        margin-right: 5px;
        font-size: 14px;
      }
    }
  }

  .products-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .products-item {
      background-color: #fff;
      margin-bottom: 15px;
      position: relative;
      border-radius: 10px;
      transition: transform 0.3s, box-shadow 0.3s;
      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
      }

      .products-img-container {
        position: relative;
        border-radius: 8px 8px 0px 0px;
        overflow: hidden;
        width: 100%;
        .products-tag {
          position: absolute;
          top: 5px;
          right: 5px;

          font-size: 12px;
          padding: 2px 8px;
          border-radius: 10px;
        }
        .hot {
          background-color: #ff6b6b;
          color: #fff;
        }
        .new {
          background-color: #ffd166;
          color: #111;
        }
      }

      .products-content-container {
        display: flex;
        flex-direction: column;
        padding: 5px 10px 5px 10px;
        .products-name {
          font-size: 20px;
          font-weight: 700;
          color: #333;
        }

        .products-desc {
          font-size: 16px;
          color: #999;
          margin: 5px 0px;
        }

        .products-price {
          font-size: 18px;
          color: #ff8a3c;
          font-weight: 600;
        }
      }
    }
  }
}
</style>
